package com.goldenlight.fvms.manager.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.goldenlight.fvms.manager.entity.EmployFreeApply;
import com.goldenlight.fvms.manager.entity.FreeApply;
import com.goldenlight.fvms.manager.entity.ProductFreeApply;
import com.goldenlight.fvms.manager.idgenerator.service.IdService;
import com.goldenlight.fvms.manager.service.EmployFreeApplyService;
import com.goldenlight.fvms.manager.service.FreeApplyService;
import com.goldenlight.fvms.manager.service.ProductFreeApplyService;
import com.goldenlight.fvms.manager.utils.CommonUtils;
import com.goldenlight.fvms.manager.utils.ExcelUtils;
import com.goldenlight.fvms.manager.utils.GlobalCont;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ProductFreeCarApplyFilter implements Filter {
    @Override
    public void doFilter(Request request, Response response, FilterChain filterChain) {
        Map<String, Object> req = request.getData();
        Integer type = (Integer) req.get("type");
        if (type != 5) {
            Map<String, Object> result = doRequest(request, response, filterChain);
            filterChain.doFilter(request, response, filterChain);
            if ((Integer) result.get("code") == 530) {//有重复记录
                response.setResponse(com.goldenlight.fvms.manager.vo.Response.build(530, "repeat", result));
            } else if ((Integer) result.get("code") == 200) {//成功
                response.setResponse(com.goldenlight.fvms.manager.vo.Response.build(200, "success", result));
            } else if ((Integer) result.get("code") == 540) {//车牌重复，姓名不重复
                response.setResponse(com.goldenlight.fvms.manager.vo.Response.build(540, "warn", result));
            } else if ((Integer) result.get("code") == 550) {
                response.setResponse(com.goldenlight.fvms.manager.vo.Response.build(550, "warn", result));
            } else if ((Integer) result.get("code") == 510) {
                response.setResponse(com.goldenlight.fvms.manager.vo.Response.build(510, "warn", result));
            }
        } else {
            filterChain.doFilter(request, response, filterChain);
        }

    }


    private Map<String, Object> doRequest(Request request, Response response, FilterChain filterChain) {
        Map<String, Object> req = request.getData();
        Logger logger = (Logger) req.get("logger");
        int type = (int) req.get("type");
        String buildVersion = (String) req.get("buildVersion");
        ProductFreeApplyService productFreeApplyService = (ProductFreeApplyService) req.get("producService");
        IdService idService = (IdService) req.get("idService");
        FreeApplyService freeApplyService = (FreeApplyService) req.get("parentService");
        String oldVersion = getOldVersion(type, productFreeApplyService);

        MultipartFile file = (MultipartFile) req.get("file");
        Map<String, Object> result = new HashMap<String, Object>();//返回前台界面数据}
       // final List<String> companys = GlobalCont.list;//规定可以申请免费车的公司
        List<ProductFreeApply> listExcel = ExcelUtils.importExcel(file, 1, 2, ProductFreeApply.class);//导入excel信息
        logger.info("excel 初始导入：{}", listExcel);
      //  String carApplyUnit = listExcel.get(0).getCarApplyUnit();

        if (isExistVersion(buildVersion, freeApplyService, result)) return result;
        String currVersion = buildVersion;

        if (listExcel.size() > 0) {//筛选出存在的才进行去重
            if (dealExistInExcel(type, buildVersion, productFreeApplyService, idService, freeApplyService, oldVersion, result, listExcel, currVersion))
                return result;
        } else {
            result.put("outCompanys", listExcel);//不在申请公司内
            result.put("code", 550);
        }
        return result;
    }

    private String getOldVersion(long type, ProductFreeApplyService productFreeApplyService) {
        QueryWrapper<ProductFreeApply> oldVersionQuery = new QueryWrapper<>();
        oldVersionQuery.lambda().eq(ProductFreeApply::getCarType, type).orderByDesc(ProductFreeApply::getTimeStamp);
        List<ProductFreeApply> oldList = productFreeApplyService.list(oldVersionQuery);
        return oldList.isEmpty() ? "" : oldList.get(0).getBuildVersion();
    }

    private boolean isExistVersion(String buildVersion, FreeApplyService freeApplyService, Map<String, Object> result) {
        FreeApply one = getBuildVersion(buildVersion, freeApplyService);
        if (null != one) {
            result.put("code", 510);
            return true;
        }
        return false;
    }

    private boolean dealExistInExcel(int type, String buildVersion, ProductFreeApplyService productFreeApplyService, IdService idService, FreeApplyService freeApplyService, String oldVersion, Map<String, Object> result, List<ProductFreeApply> listExcel, String currVersion) {
        Map<String, List<ProductFreeApply>> collect = listExcel.stream()
                .filter(item -> !StringUtils.isEmpty(item.getCarNum()) && !StringUtils.isEmpty(item.getCarBussType()))
                .collect(Collectors.groupingBy(ProductFreeApply::getJudgeCondition));
        List<ProductFreeApply> reList = new ArrayList();//存储筛选出重复的车牌号、申请人姓名、业务类型
        List<ProductFreeApply> dealList = new ArrayList();//存储重复的车牌号和重复申请人姓名
        getCarListInfo(collect, reList, dealList);
        result.put("reList", reList);//存储筛选出重复的车牌号、申请人姓名、业务类型
        result.put("dealList", dealList);//重复的车牌号和不重复申请人姓名

        if (reList.size() > 0) {
            result.put("code", 530);
            result.put("reList", reList);
            return true;
        } else {
            dealNoRepeatInfo(type, buildVersion, productFreeApplyService, idService, freeApplyService, oldVersion, result, currVersion, dealList);
        }
        return false;
    }

    private void dealNoRepeatInfo(int type, String buildVersion, ProductFreeApplyService productFreeApplyService, IdService idService, FreeApplyService freeApplyService, String oldVersion, Map<String, Object> result, String currVersion, List<ProductFreeApply> dealList) {
        CollectInfo collectInfo = new CollectInfo();
//        String oldVersion = oldList.isEmpty() ? "" : oldList.get(0).getBuildVersion();
        collectInfo.setOldVersion(oldVersion);
        Map<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("buildVersion", oldVersion);
        int count = productFreeApplyService.count(new QueryWrapper<ProductFreeApply>().lambda().eq(ProductFreeApply::getBuildVersion, oldVersion));
        collectInfo.total(StringUtils.isEmpty(oldVersion) ? 0 : count);//原有总条数
        conditionMap.put("carBussType", "新增");
        collectInfo.newTotal(StringUtils.isEmpty(oldVersion) ? 0 : productFreeApplyService.qryCount(conditionMap));//原有总新增条数
        conditionMap.put("carBussType", "已办理");
        collectInfo.dealTotal(StringUtils.isEmpty(oldVersion) ? 0 : productFreeApplyService.qryCount(conditionMap));//原有总新增条数conditionMap.put("carBussType", "新增");
        conditionMap.put("carBussType", "取消");
        collectInfo.cancelTotal(StringUtils.isEmpty(oldVersion) ? 0 : productFreeApplyService.qryCount(conditionMap));//原有总新增条数conditionMap.put("carBussType", "新增");


        dealList.stream().forEach(item -> {
            item.setCarType((long) type);
            item.setBuildVersion(currVersion);

            item.setApplyId(idService.genId());
            FreeApply freeApply = CommonUtils.convert(item, FreeApply.class);
            freeApply.setTypeCode("" + type);
            freeApply.setApplyUnit(item.getCarApplyUnit());
            freeApplyService.save(freeApply);

            productFreeApplyService.save(item);
        });

        conditionMap.put("buildVersion", currVersion);
        collectInfo.totalCurrent(productFreeApplyService.count(new QueryWrapper<ProductFreeApply>().lambda().eq(ProductFreeApply::getBuildVersion, currVersion)));//原有总条数
        conditionMap.put("carBussType", "新增");
        collectInfo.newTotalCurrent(productFreeApplyService.qryCount(conditionMap));//原有总新增条数
        conditionMap.put("carBussType", "已办理");
        collectInfo.dealTotalCurrent(productFreeApplyService.qryCount(conditionMap));//原有总新增条数conditionMap.put("carBussType", "新增");
        conditionMap.put("carBussType", "取消");
        collectInfo.cancelTotalCurrent(productFreeApplyService.qryCount(conditionMap));//原有总新增条数conditionMap.put("carBussType", "新增");
        /**
         * add 20190611
         * 导入类型
         */
        collectInfo.setSelectType(type);
        collectInfo.setBuildVersion(buildVersion);

        result.put("code", 200);
        result.put("cllectInfo", Lists.newArrayList(collectInfo));
    }

    /**
     * @param collect
     * @param reList  存储重复的车牌号、申请人姓名、业务类型信息
     * @param dealList 存储重复的车牌号和重复申请人姓名
     */
    private void getCarListInfo(Map<String, List<ProductFreeApply>> collect, List<ProductFreeApply> reList, List<ProductFreeApply> dealList) {
        collect.forEach((k, v) -> {
            if (v.size() > 1) {
                v.forEach(item -> {
                    if (null != k) {
                        reList.add(item);
                    }
                });
            } else if (v.size() == 1) {
                v.forEach(item -> {
                    dealList.add(item);


                });
            }
        });
    }

    /**
     * 查询版本号是否已经存在
     */
    private FreeApply getBuildVersion(String buildVersion, FreeApplyService freeApplyService) {
        return freeApplyService.getOne(new QueryWrapper<FreeApply>().lambda().eq(FreeApply::getBuildVersion, buildVersion));
    }

}
